import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:hockey/services/jzx_config.dart';
// import 'package:hockey/services/jzx_rongcloud.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import 'package:hockey/pages/jzx_login/jzx_login.dart';

import '../jzx_models.dart';
import '../jzx_tabbar.dart';
import '../network/jzx_repository.dart';
import '../utils/jzx_common.dart';
import '../widgets/common/jzx_toast.dart';
import 'jzx_app.dart';

const _kAppToken = 'k_app_token';
const _kUser = 'k_user';
const _kUserLevel = 'k_user_level';
const _kUserWear = 'k_user_wear';

/// 用户相关的全局处理
class JzxUserService extends GetxService {
  static JzxUserService get to => Get.find();
  final box = GetStorage();

  /// 用户是否登录
  bool get isLogined => tokenData.token.isNotEmpty;

  /// 用户ID
  String get uid => tokenData.userInfo.userId;

  /// 可用余额
  num get balance => user.value.availableCoins;

  /// 头像
  String get avatar => user.value.avatarUrl;
  String get nickname => user.value.nickname;
  String get birthday => user.value.birthday;
  String get country {
    return user.value.registerCountry == 'CN'
        ? 'US'
        : user.value.registerCountry;
  }

  /// 当前用户的作者名称
  String get author => 'jzx';

  /// 构建当前用户作者信息
  JzxAuthorData get authorData => JzxAuthorData(
        avatar: avatar,
        nickname: nickname,
        userId: uid,
        country: country,
        level: userWear.value,
      );

  /// 身份鉴权
  var tokenData = const JzxTokenData();

  /// 用户信息
  var user = const JzxUserData().obs;

  /// 配置信息
  var config = const JzxConfigData();

  /// 当前等级 本地
  var userLevel = <int>[].obs;

  /// 佩戴等级 本地
  var userWear = 0.obs;

  /// 用户佩戴头像框level是否升级
  bool get userWearIsUpgrade {
    for (var element in frameList) {
      if (element.value.level == userWear.value) {
        return element.value.isUpgrade;
      }
    }
    return false;
  }

  /// 解锁任务信息
  var frameList = <Rx<JzxCdtItem>>[];
  var orginFrameList = [
    JzxCdtItem(1, 'Log in to get it.'),
    JzxCdtItem(2, 'Like three articles about hockey.', number: 3),
    JzxCdtItem(3, 'Like three videos about hockey.', number: 3),
    JzxCdtItem(4, 'Follow three hockey users.', number: 3),
    JzxCdtItem(5, 'Post an article about hockey.', number: 1),
  ];

  @override
  void onInit() async {
    initLevel();
    initStroage();
    initConditions();
    super.onInit();

    // 获取配置
    config = await JzxNetRepository.client.getAppConfig();
  }

  /// 初始化本地存储 用户/token
  initStroage() {
    Map<String, dynamic> tokenStr = box.read(_kAppToken) ?? {};
    if (tokenStr.isNotEmpty) {
      // 获取本地鉴权信息
      tokenData = JzxTokenData.fromJson(tokenStr);
      // 获取用户信息
      Map<String, dynamic> userStr = box.read(_kUser) ?? {};
      if (userStr.isNotEmpty) {
        user.value = JzxUserData.fromJson(userStr);
      }
    }
  }

  /// 判断是否需要登录
  Future<bool> isNeedLogin() async {
    if (isLogined) {
      try {
        // 鉴权
        await JzxNetRepository.client.validToken({'token': tokenData.token});

        updateUser();
        return false;
      } catch (e) {
        cleanUserCache();
        return true;
      }
    }
    return true;
  }

  /// 更新用户信息
  updateUser() async {
    user.value = await JzxNetRepository.client.user(uid);
    box.write(_kUser, user.value.toJson());

    if (config.rcAppKey.isNotEmpty) {
      // JzxRCloudService.to.connect();
    }
  }

  /// 登陆
  login(int type) async {
    try {
      showLoading();

      var params = {
        'oauthType': type.toString(),
        // 'token': identifier,
      };
      if (type == 3) {
        final credential = await SignInWithApple.getAppleIDCredential(
          scopes: [
            AppleIDAuthorizationScopes.email,
            AppleIDAuthorizationScopes.fullName,
          ],
        );
        params['token'] = credential.identityToken ?? '';
      } else {
        params['token'] = JzxAppService.to.device.identifier;
      }

      tokenData = await JzxNetRepository.client.login(params);

      if (!tokenData.isFirstRegister) {
        // 第一次登陆显示level1弹框
        box.write(kNotShowLevelPop, true);
      }
      // 缓存token
      box.write(_kAppToken, tokenData.toJson());

      // 用户信息
      updateUser();
      JzxLogPvManger.tracking(page: JzxLogPages.loginsuccess);

      Get.offAllNamed(kRouteTabbar);
    } catch (e) {
      // log('$e');
    }

    hideLoading();
  }

  /// 登出
  logout() async {
    showLoading();
    await JzxNetRepository.client.logout();
    hideLoading();
    cleanUserCache();
    // im
    // JzxRCloudService.to.disconnect();

    // others
    Get.offAllNamed(kRouteJzxLogin);
  }

  /// 清除缓存
  cleanUserCache() {
    JzxAppService.to.rest();
    tokenData = const JzxTokenData();
    user.value = const JzxUserData();

    box.remove(_kAppToken);
    box.remove(_kUser);
  }

  /// 注销账户
  unsubscribeUser() async {
    showLoading();
    await JzxNetRepository.client.deleteAccount();

    await box.erase();
    await box.save();

    // for (var i = 1; i <= frameList.length; i++) {
    //   box.remove('frame_done_$i');
    //   box.remove('frame_upgrade_$i');
    // }

    // await box.remove(_kUser);
    // await box.remove(_kAppToken);
    // await box.remove(_kUserLevel);
    // await box.remove(_kUserWear);
    // await box.remove(kNotShowLevelPop);
    // // await box.remove(kFirstLaunch);
    // await box.remove(kPostListKey);
    // await box.remove(kVideoListKey);
    // await box.remove(kBindListKey);
    // await box.remove(kUsersKey);
    // await box.remove(kFollowUsers);
    // await box.remove(kBlockUsers);
    // await box.remove(kCommentListKey);

    box.write(kFirstLaunch, true);
    hideLoading();

    cleanUserCache();
    JzxConfigService.to.reset();
    rest();
    Get.offAllNamed(kRouteJzxLogin);
  }

  rest() {
    initLevel();
    initStroage();
    initConditions();
  }

  // -------------------------- 等级解锁条件 ----------------------------

  /// 初始化解锁条件,已完成的任务数
  initConditions() {
    frameList.clear();
    for (var i = 0; i < orginFrameList.length; i++) {
      frameList.add(
        Rx(
          orginFrameList[i].copyWith(
            done: box.read('frame_done_${i + 1}') ?? 0,
            isUpgrade: box.read('frame_upgrade_${i + 1}') ?? false,
          ),
        ),
      );
    }
    // print(frameList);
  }

  /// 更新解锁条件
  /// 外部完成任务后调用
  updateUnlockConditions(int level) {
    final item = frameList[level - 1];
    item.value = item.value.increment();
    if (item.value.done == item.value.number) {
      updateUserLevel(level);
      JzxAppService.bus.fire(FulfilTask(level));
    }
    //
    for (var i = 1; i <= frameList.length; i++) {
      box.write('frame_done_$i', frameList[i - 1].value.done);
    }
  }

  /// 升级高级头像框
  updateUnlockUpgrade(int level) {
    final item = frameList[level - 1];
    item.value = item.value.upgrade();
    for (var i = 1; i <= frameList.length; i++) {
      box.write('frame_upgrade_$i', frameList[i - 1].value.isUpgrade);
    }
  }

  // -------------------------- 用户等级处理 ----------------------------
  /// 初始化用户等级/穿戴等级
  initLevel() {
    userLevel.clear();
    userWear.value = 0;
    final temp = box.read(_kUserLevel);
    if (temp is List) {
      for (var element in temp) {
        final lev = int.tryParse('$element') ?? 0;
        if (lev > 0) {
          userLevel.add(lev);
        }
      }
    }
    // userLevel.value = box.read(_kUserLevel) ?? <int>[];
    userWear.value = box.read(_kUserWear) ?? 0;
  }

  /// 是否拥有等级
  bool isOwnLevel(int level) {
    return JzxUserService.to.userLevel.value.contains(level);
  }

  /// 更新用户等级
  void updateUserLevel(int level) {
    userLevel.remove(level);
    userLevel.value.add(level);

    box.write(_kUserLevel, userLevel.value);
  }

  /// 佩戴头像框
  void updateUserWear([int? level]) {
    userWear.value = level ?? userWear.value;
    box.write(_kUserWear, level ?? userWear.value);
  }
}
